package org.ykh.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.ykh.srb.core.mapper.DictMapper;
import org.ykh.srb.core.pojo.dto.ExcelDictDTO;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;


/**
 * @author ykh
 */
@Slf4j
@Scope(SCOPE_PROTOTYPE)
@Component
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private List<ExcelDictDTO> list = new ArrayList<ExcelDictDTO>();

    private final DictMapper dictMapper;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {
        log.debug("解析excel数据:{}", data);
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.debug("{}条数据，开始存储数据库！", list.size());
        dictMapper.insertBatch(list);  //批量插入
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
    }

}
